package com.common.server.modules.qrcode.controller;

import com.common.server.common.response.ResponseVo;
import com.common.server.common.util.FileUtil;
import com.common.server.modules.qrcode.entity.ZXingCode;
import com.common.server.modules.qrcode.service.QRCodeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

/**
 * 描述：二维码服务 前端控制器
 * <p>
 * 作者：Ostrich Hu
 * 时间：2019/10/12 15:36 星期六
 */
@Api(tags = "二维码")
@RestController
@RequestMapping("api/rest/file")
public class QRCodeController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${sys.config.uploadFilePath}")
    private String uploadPath;

    @Autowired
    private QRCodeService qrCodeService;

    @ApiOperation("生成二维码-默认logo")
    @PostMapping(value = "/genZXingCode")
    public void genZXingCode(ZXingCode zXingCode, HttpServletRequest request, HttpServletResponse response) {
        qrCodeService.genZXingCode(zXingCode, request, response);
    }

    @ApiOperation("生成二维码-自定义logo")
    @PostMapping(value = "/genZXingSelfCode")
    public void genZXingSelfCode(ZXingCode zXingCode, @RequestParam("file") MultipartFile file,
                                 HttpServletRequest request, HttpServletResponse response) {
        qrCodeService.genZXingSelfCode(file, zXingCode, request, response);
    }

    @ApiOperation("解析二维码")
    @PostMapping(value = "/decode")
    public ResponseVo decodeZXingQR(@RequestParam("file") MultipartFile multipartFile) {

        try {
            String originalFilename = multipartFile.getOriginalFilename();
            String filePath = uploadPath + "qQdecode" + File.separator;
            String fileName = FileUtil.saveFile(multipartFile.getInputStream(), originalFilename, filePath);
            File file = new File(filePath + fileName);
            return new ResponseVo(0, "解析成功", qrCodeService.decode(file));
        } catch (IOException e) {
            return ResponseVo.error("解析二维码文件失败");
        }
    }

}
